package com.ruoyi.flowable.cmd;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.flowable.exception.FlowableException;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import org.flowable.bpmn.converter.BpmnXMLConverter;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.Model;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.Serializable;

/**
 * @program: RuoYi-Vue
 * @description: 部署流程模型
 * @author: jhw
 * @create: 2021-04-08 10:30
 **/
public class DeployModelCmd implements Command<Void>, Serializable {
    private static final long serialVersionUID = -8674075847552256221L;
    private String modelId;

    public DeployModelCmd(String modelId) {
        this.modelId = modelId;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        RepositoryService repositoryService = CommandContextUtil.getProcessEngineConfiguration(commandContext).getRepositoryService();

        if(StringUtils.isEmpty(modelId)){
            throw new FlowableException("flowable.model.deployModelError",new Object[]{"modelId  is null !"});
        }

        Model model = repositoryService.getModel(modelId);
        if (model==null){
            throw new FlowableException("flowable.model.deployModelError",new Object[]{"根据ID未找到流程: !"+modelId});
        }
        byte[] xml = repositoryService.getModelEditorSource(modelId);
        if(xml==null || !model.hasEditorSource()){
            throw new FlowableException("flowable.model.deployModelError",new Object[]{"根据ID未找到流程模型XML: !"+modelId});
        }

        try {
            BpmnXMLConverter converter = new BpmnXMLConverter();
            XMLInputFactory xif = XMLInputFactory.newInstance();
            InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(xml),"UTF-8");
            XMLStreamReader xmlSr = xif.createXMLStreamReader(isr);
            BpmnModel bpmnModel = converter.convertToBpmnModel(xmlSr);

            Deployment deployment = repositoryService.createDeployment().addBpmnModel(model.getName()+ ".bpmn20.xml",bpmnModel).deploy();
            model.setDeploymentId(deployment.getId());

        }catch (Exception e){
            throw  new FlowableException("flowable.model.deployModelError",new Object[]{e.getMessage()});
        }
        return null;
    }
}
